﻿using System;
using System.Collections.Generic;
using System.Text;
using JsonSharp.Collections;
using Barbar.MapReport.HtmlRender.Operations.ValueIndicators;
using JsonSharp.Values;
using Barbar.MapReport.Common.Drawing.ValueIndicators;
using Barbar.MapReport.HtmlRender.Shapes;

namespace Barbar.MapReport.HtmlRender.Json {
  internal class ValueIndicatorAgregatorFactory : JsonFactory {
    private ValueIndicatorAgregator m_Agregator;
    private BaseProperties m_Properties;
    private string m_HandlerUrl;

    private IValueIndicatorAgregatorRenderer CreateRenderer() {
      BusinessProperties businessProperties = m_Properties as BusinessProperties;
      if (businessProperties != null)
        return new ValueIndicatorAgregatorBusinessRenderer(businessProperties);

      GroupProperties groupProperties = m_Properties as GroupProperties;
      if (groupProperties != null)
        return new ValueIndicatorAgregatorGroupRenderer(groupProperties);

      ListProperties listProperties = m_Properties as ListProperties;
      if (listProperties != null)
        return new ValueIndicatorAgregatorListRenderer(listProperties);

      throw new NotImplementedException();
    }
    

    public ValueIndicatorAgregatorFactory(ValueIndicatorAgregator agregator, BaseProperties properties, string handlerUrl) {
      if (agregator == null)
        throw new ArgumentNullException("agregator");
      if (properties == null)
        throw new ArgumentNullException("properties");
      if (String.IsNullOrEmpty(handlerUrl))
        throw new ArgumentNullException("handlerUrl");

      m_Agregator = agregator;
      m_Properties = properties;
      m_HandlerUrl = handlerUrl;
    }

    public override JsonSharp.JsonValue ToJsonObject() {
      JsonObjects result = new JsonObjects();
      int realRadius = m_Agregator.RealRadius;
      result.Add(new JsonStringValue("radius"), new JsonNumberValue(realRadius));
      result.Add(new JsonStringValue("point"), new GeoPointFactory(m_Agregator.GeoPoint).ToJsonObject());
      
      IValueIndicatorAgregatorRenderer renderer = CreateRenderer();
      ShapeWithTooltip shapeWithTooltip = renderer.Render(m_Agregator);
      result.Add(new JsonStringValue("url"), new JsonStringValue(ShapeHandler.GetURL(shapeWithTooltip.Shape).ToString(m_HandlerUrl)));

      if (shapeWithTooltip.Tooltip != null)
        result.Add(new JsonStringValue("description"), new JsonStringValue(shapeWithTooltip.Tooltip));
      return result;
    }
  }
}
